<template>
  <router-link
    v-if="product"
    :to="`/product/${product.id}`"
    class="product-card bg-white rounded-lg shadow-sm overflow-hidden transition-all duration-300 hover:shadow-md hover:-translate-y-1 group relative"
    :class="{
      flex: size === '2x2',
    }"
    ref="productCardRef"
  >

    <div
      class="product-image relative overflow-hidden bg-white flex items-center justify-center"
      :class="[
        size === '1x1' ? 'h-48' : '',
        size === '2x1' ? 'h-48' : '',
        size === '2x2' ? 'h-[400px] w-1/2' : '',
      ]"
    >
      <div
        v-if="isLoading"
        class="absolute inset-0 flex items-center justify-center"
      >
        <div class="loading-spinner">
          <div class="medical-cross">
            <div class="cross-horizontal"></div>
            <div class="cross-vertical"></div>
          </div>
        </div>
      </div>
      <img
        v-show="!isLoading"
        :src="imageUrl"
        :alt="product.name"
        class="h-full object-contain product-img"
        @load="handleImageLoad"
        @error="handleImageError"
        loading="lazy"
        ref="productImage"
      />
    </div>

    <div
      class="product-info p-3 !bg-white flex flex-col justify-between"
      :class="{
        'w-1/2 h-96': size === '2x2',
      }"
    >
      <div>
        <h3 class="text-base font-medium text-gray-800 mb-2 line-clamp-2 product-title">
          {{ product.name }}
        </h3>
        <div class="space-y-1 product-details">
          <div class="text-sm text-gray-600">{{ product.manufacturer }}</div>
          <div class="text-sm text-gray-600">
            规格: {{ product.specification }}
          </div>
          <div class="text-sm text-gray-600">{{ product.unit }}</div>
          
          <!-- 近效期信息 -->
          <div v-if="product.nearestExpiredDate" class="batch-info space-y-1">
            <div class="text-xs text-gray-500">
              <span>有效期: </span>
              <span class="text-orange-600 font-medium">{{ formatDate(product.nearestExpiredDate) }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="flex items-center justify-between mt-3">
        <div class="price-section">
          <span class="product-price text-lg font-bold text-red-600">
            {{ formatPriceAuth(product.price, !!userStore.token, userStore.userInfo?.discount, product.noDiscounts) }}
          </span>
          <span v-if="userStore.userInfo?.discount && product.noDiscounts !== 1" class="text-gray-500 text-sm ml-2 line-through">
            {{ formatPriceAuth(product.price, !!userStore.token) }}
          </span>
        </div>
        <div class="text-sm text-gray-500">已售: {{ product.salesVolume }}</div>
      </div>
    </div>
  </router-link>
  <div
    v-else
    class="product-card bg-white rounded-lg shadow-sm overflow-hidden"
  >
    <el-skeleton :rows="3" animated />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from "vue";
import { useImage } from "@vueuse/core";
import type { DisplayGoods } from "@/views/HomeView.vue";
import { useUserStore } from "@/stores/user";
import { handleImageError as handleImgError, getImageSrc } from '@/lib/imageUtils';
import { animations, animationUtils } from '@/components/animations/GSAPAnimations';
import { formatPriceAuth } from '@/lib/utils';

const userStore = useUserStore();

const props = defineProps<{
  product: DisplayGoods | null;
  size?: "1x1" | "2x1" | "2x2";
  animationDelay?: number;
}>();

// Template refs
const productCardRef = ref<HTMLElement | null>(null);
const productImage = ref<HTMLImageElement | null>(null);
const prescriptionBadgeRef = ref<HTMLElement | null>(null);
const priceRef = ref<HTMLElement | null>(null);

const isLoading = ref(true);

// Animation instances
let hoverAnimation: gsap.core.Timeline | null = null;
let badgeAnimation: gsap.core.Timeline | null = null;

const imageUrl = computed(() => {
  return getImageSrc(props.product?.imgUrl);
});

const { isReady } = useImage({ src: imageUrl.value });

function handleImageLoad() {
  isLoading.value = false;
  nextTick(() => {
    // Simple price animation when image loads
    if (priceRef.value) {
      animations.priceAnimation(priceRef.value);
    }
  });
}

function handleImageError(event: Event) {
  handleImgError(event);
  isLoading.value = false;
}

function setupHoverAnimation() {
  if (!productCardRef.value) return;

  // Simple hover animation
  hoverAnimation = animations.productCardHover(productCardRef.value);

  const card = productCardRef.value;
  
  card.addEventListener('mouseenter', () => {
    if (hoverAnimation) {
      hoverAnimation.play();
    }
  });

  card.addEventListener('mouseleave', () => {
    if (hoverAnimation) {
      hoverAnimation.reverse();
    }
  });
}

function setupBadgeAnimation() {
  if (prescriptionBadgeRef.value) {
    const badge = prescriptionBadgeRef.value.querySelector('.prescription-badge') as Element;
    if (badge) {
      badgeAnimation = animations.prescriptionBadge(badge);
    }
  }
}

onMounted(() => {
  nextTick(() => {
    setupHoverAnimation();
    setupBadgeAnimation();
  });
});

onUnmounted(() => {
  if (hoverAnimation) animationUtils.cleanup(hoverAnimation);
  if (badgeAnimation) animationUtils.cleanup(badgeAnimation);
});

// Watch for image readiness
watch(isReady, (ready) => {
  if (!ready) {
    isLoading.value = true;
  }
});

// 格式化日期函数
function formatDate(dateString: string): string {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return dateString
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    
    return `${year}-${month}-${day}`
  } catch (error) {
    return dateString
  }
}
</script>

<style scoped>
.product-card {
  @apply relative;
}

.product-image {
  @apply transition-opacity duration-300;
}

.product-image img {
  @apply transition-opacity duration-300;
}

/* Medical Cross Loading Animation */
.loading-spinner {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
}

.medical-cross {
  position: relative;
  width: 24px;
  height: 24px;
}

.cross-horizontal,
.cross-vertical {
  position: absolute;
  background-color: #dc2626;
  border-radius: 2px;
  animation: pulse 1.5s infinite;
}

.cross-horizontal {
  width: 24px;
  height: 4px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation-delay: 0s;
}

.cross-vertical {
  width: 4px;
  height: 24px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation-delay: 0.3s;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
  50% {
    opacity: 0.7;
    transform: translate(-50%, -50%) scale(0.8);
  }
}

/* Prescription Badge Styling */
.prescription-badge {
  position: relative;
  overflow: hidden;
}

.prescription-badge::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.6s;
}

.prescription-badge:hover::before {
  left: 100%;
}

/* Enhanced Product Card Effects */
.product-card:hover .product-img {
  transform: scale(1.05);
  transition: transform 0.3s ease;
}

.product-title {
  transition: color 0.3s ease;
}

.product-card:hover .product-title {
  color: #2563eb;
}

.product-price {
  position: relative;
  transition: all 0.3s ease;
}

.product-card:hover .product-price {
  transform: scale(1.05);
}

/* Mobile optimizations */
@media (max-width: 768px) {
  .product-card:hover .product-img {
    transform: none;
  }
  
  .product-card:hover .product-price {
    transform: none;
  }
}
</style>
